package com.itheima.web.servlet; /**
 * @author Xiao
 * @date 2021/9/8
 */

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/selectByPageServlet")
public class SelectByPageServlet extends HttpServlet {
    /**
     * 分页查询(LIMIT)
     *     SELECT 字段列表 FROM 表名 LIMIT  起始索引 , 查询条目数;
     *     注意：第一页的起始索引从0开始，第一个编号通常从1开始。
     *     计算公式：起始索引 = (当前页码-1) * 每页显示的条数
     */
    private final BrandServiceImpl brandService = new BrandServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = request.getParameter("page");
        String count = request.getParameter("pageSize");
        Integer index = (Integer.parseInt(page) - 1) * Integer.parseInt(count);
        PageBean<Brand> pageBean = brandService.selectByPage(index, Integer.parseInt(count));
        String jsonPageBean = JSON.toJSONString(pageBean);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(jsonPageBean);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
